package com.ly.controller;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.map.MapUtil;
import com.google.code.kaptcha.Producer;
import com.ly.base.ResponseData;
import com.ly.entity.SysRole;
import com.ly.entity.SysUser;
import com.ly.entity.SysUserRole;
import com.ly.lang.Const;
import com.ly.utils.DateUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.Principal;
import java.util.Date;

@Api(description = "验证码")
@RestController
public class AuthController extends BaseController{

    @Autowired
    private Producer producer;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @ApiOperation(value="获取验证码")
    @GetMapping("/captcha")
    public ResponseData captcha() throws IOException {
        String key = UUID.randomUUID().toString();
        String code = producer.createText();

        BufferedImage image = producer.createImage(code);
        // 转换为baes64
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", outputStream);
        BASE64Encoder base64Encoder = new BASE64Encoder();
        String str = "data:image/jpeg;base64,";
        String base64Image = str + base64Encoder.encode(outputStream.toByteArray());
        this.redisUtil.hset(Const.CAPTCHA_KEY, key, code, 120);
        return ResponseData.success(MapUtil.builder().
                put("token", key).
                put("captchaImg", base64Image).
                build());
    }

    @ApiOperation(value="获取用户信息")
    @GetMapping("/sys/userInfo")
    public ResponseData userInfo(Principal principal){
        SysUser byUserName = sysUserService.getByUserName(principal.getName());
        return ResponseData.success(MapUtil.builder().
                put("id", byUserName.getId()).
                put("userName", byUserName.getUserName()).
                put("avatar", byUserName.getAvatar()).
                put("createdAt", byUserName.getCreatedAt()).
                put("name",byUserName.getName()).
                put("roleCode",byUserName.getSysRole().getCode()).
                put("balance",byUserName.getBalance()).
                map());
    }

    @ApiOperation(value="注册账号")
    @PostMapping("/addUser")
    public ResponseData addUser(SysUser sysUser){

        SysUser sysUser1 = sysUserService.getByUserName(sysUser.getUserName());
        if(sysUser1!=null){
            return ResponseData.fail("该账号已注册!");
        }

        //默认头像
        sysUser.setAvatar(Const.DEFULT_AVATAR);

        // 默认密码
        String password = bCryptPasswordEncoder.encode(sysUser.getPassword());

        sysUser.setPassword(password);
        sysUser.setCreatedAt(DateUtils.getYyyyMMddHHmmss(new Date()));
        sysUserService.save(sysUser);

        SysRole sysRole  = sysRoleService.getByCode("normal");
        if(sysRole!=null){

            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(sysRole.getId());
            sysUserRole.setUserId(sysUser.getId());
            sysUserRoleService.save(sysUserRole);
        }

        return ResponseData.success(sysUser);
    }

}
